package org.ysling.litemall.core.config;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.ysling.litemall.core.util.IpUtil;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;

/**
 * 接口切面日志
 */
@Configuration
public class LogAspectConfig {

    private Log logger = LogFactory.getLog(LogAspectConfig.class);

    /**
     * 配置切入点表达式
     */
    private static final String POINTCUT_EXPRESSION = "execution(* org.ysling.litemall.*.web.*.*(..))";

    /**
     * 日志的切面
     * @return
     */
    @Bean
    public DefaultPointcutAdvisor defaultPointcutAdvisor2() {
        //添加切点
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(POINTCUT_EXPRESSION);
        //环绕通知方法
        MethodInterceptor interceptor = new MethodInterceptor() {
            @Nullable
            @Override
            public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
                long start = System.currentTimeMillis();
                Object result = invocation.proceed();
                long end = System.currentTimeMillis();

                logger.info("=====================================Method  start==================================");
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes == null) return result;
                HttpServletRequest request = attributes.getRequest();
                logger.info("请求地址:" + request.getRequestURI());
                logger.info("用户IP:" + IpUtil.getIpAddr(request));
                logger.info("执行时间: " + (end - start) + " ms!");
                logger.info("=====================================Method  End====================================");
                return result;
            }
        };
        // 配置增强类advisor
        DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
        advisor.setPointcut(pointcut);
        advisor.setAdvice(interceptor);
        return advisor;
    }
}